package cn.ex.ymcc.mq.consumer;

import cn.ex.ymcc.domain.PayOrder;
import cn.ex.ymcc.dto.PayDto;
import cn.ex.ymcc.service.IPayOrderService;
import cn.ex.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 课程订单生成支付单的消费者
 *
 */
@Component
@RocketMQMessageListener(
        consumerGroup="course-order-pay-consumer",
        topic="course-order-topic",
        selectorExpression="course-order-tag",
        messageModel = MessageModel.CLUSTERING  //集群模式
)
@Slf4j
public class Courser2PayConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    /**
     * 消费消息
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        //校验
        AssertUtil.isNotNull(body,"消息体为空！！");
        String jsonStr = new String(body, StandardCharsets.UTF_8);
        PayDto payDto = JSONObject.parseObject(jsonStr, PayDto.class);
        //查询支付单是否存在
        PayOrder payOrder = payOrderService.selectByOrderNo(payDto.getOrderNo());
        if(payOrder != null){
            log.info("订单已经存在，不再消费消息，直接签收！！");
            return;//不报错即签收
        }
        //不存在保存支付单
        payOrder = new PayOrder();
        BeanUtils.copyProperties(payDto,payOrder);
        payOrder.setCreateTime(new Date());
        payOrder.setPayStatus(PayOrder.STATE_WAIT_PAY);
        payOrderService.insert(payOrder);
    }
}
